import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { useHistory } from 'react-router-dom'
import styles from './index.module.scss'
import { useEffect, useRef, useState } from 'react'
import io from 'socket.io-client'
import { base } from '@/utils/request'
import { useSelector } from 'react-redux'
const Chat = () => {
  const element = useRef(null)
  const history = useHistory()
  const token = useSelector((state) => state.login.token)
  const photo = useSelector((state) => state.profile.user.photo)
  const [list, setList] = useState([])

  const clientRef = useRef()
  useEffect(() => {
    // console.log(123)
    // element.current.scrollIntoView({ behavior: 'smooth' })
    element.current.scrollTop = element.current.scrollHeight
  }, [list])

  useEffect(() => {
    // 建立链接
    const client = io(base, {
      query: {
        token
      },
      transports: ['websocket']
    })
    clientRef.current = client
    client.on('connect', () => {
      setList((list) => {
        return [
          ...list,
          {
            type: 'BOT',
            text: '亲你好'
          }
        ]
      })
    })
    client.on('message', function (data) {
      setList((list) => {
        const { msg } = data
        return [...list, { type: 'BOT', text: msg }]
      })
    })
    return () => {
      client.close()
    }
  }, [token])

  const handleSend = (e) => {
    const val = e.target.value
    console.log(val.trim() === '')
    if (e.keyCode !== 13 || val.trim() === '') return
    console.log(123)
    clientRef.current.emit('message', {
      msg: val,
      timestamp: Date.now()
    })
    setList((list) => {
      return [
        ...list,
        {
          type: 'user',
          text: val
        }
      ]
    })
    e.target.value = ''
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className='fixed-header' onLeftClick={() => history.go(-1)}>
        小智同学
      </NavBar>

      {/* 聊天记录列表 */}
      <div className='chat-list' ref={element}>
        {list.map((item, index) => {
          if (item.type === 'BOT') {
            /* 机器人的消息 */
            return (
              <div key={index} className='chat-item'>
                <Icon type='iconbtn_xiaozhitongxue' />
                <div className='message'>{item.text}</div>
              </div>
            )
          } else {
            /* 用户的消息 */
            return (
              <div key={index} className='chat-item user'>
                <img
                  src={
                    photo || 'http://toutiao.itheima.net/images/user_head.jpg'
                  }
                  alt=''
                />
                <div className='message'>{item.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className='input-footer'>
        <Input
          className='no-border'
          placeholder='请描述您的问题'
          onKeyUp={handleSend}
        />
        <Icon type='iconbianji' />
      </div>
    </div>
  )
}

export default Chat
